package com.lightdz.tshirtdz.controller;

import com.lightdz.tshirtdz.general.ApiConfig;
import com.lightdz.tshirtdz.model.Enum.ResponseEnum;
import com.lightdz.tshirtdz.model.api.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.*;
import java.util.UUID;

@Controller
@RequestMapping("/upload")
public class ImageUpLoadController implements WebMvcConfigurer {

@Autowired
    private ApiConfig apiConfig;

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("ImageUpLoad");
}

    //跳转到html测试页
    @RequestMapping(value = "/imageUpLoad", method = RequestMethod.GET)
    public String getUpload() {
        return "ImageUpLoad.html";
    }

    @RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
    @ResponseBody
    public ApiResponse uploadImage(@RequestParam(value = "file") MultipartFile file) throws RuntimeException {

        //获取项目根目录
        File rootDirectory = new File(this.getClass().getResource("/").getPath());

        ApiResponse returnInfo = ApiResponse.getNoResponse();

        if (file.isEmpty()) {
            returnInfo = new ApiResponse( ResponseEnum.Failure.name(),null,false);
            return returnInfo;
        }

        // 获取文件名
        String fileName = file.getOriginalFilename();

        // 获取文件的后缀名
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        Boolean isImage = false;
        //定义允许上传的文件扩展名
        String[] allowExtension = {".jpg", ".jpeg", ".gif", ".bmp", ".png", ".JPG", ".JPEG", ".GIF", ".BMP", ".PNG"};
        for (int i = 0; i < allowExtension.length; i++) {
            if (suffix.equals(allowExtension[i])) {
                isImage = true;
                break;
            } else {
                isImage = false;
            }
        }
        if (!isImage) {
            returnInfo = new ApiResponse("文字直播图片上传-->照片类型错误！", ResponseEnum.PhotoTypeError, false);
            return returnInfo;
        }

        // 文件上传后的路径 D:\svn\DataCenter\BaseCenter\branches\DataCenter\DC.FrameWork\EastMoney.TextLive-java\Code\textlive\target\classes\ImagePath
        String filePath = rootDirectory.toString() +"\\" + "ImagePath";
        // uuid文件命名
        fileName = UUID.randomUUID() + suffix;
        File dest = new File(filePath + File.separator + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            OutputStream out = new FileOutputStream(dest);
            InputStream in = file.getInputStream();

            byte[] buffer = new byte[1024 * 1024];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }

            //访问路径 http://61.129.248.229/ImgPath/459fc855-d0bf-44e0-a03e-08bd348bfc5d.jpg
            String accessPath = apiConfig.getImgUploadDir() + fileName;

            in.close();
            out.close();

            returnInfo = new ApiResponse("文件上传成功",accessPath, true);

        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return returnInfo;
    }
}
